<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><%= title %></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
    <link rel='stylesheet' href='/stylesheets/style.css'>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io.connect('http://localhost:3000'); // 客户端通过io.connect()方法建立连接
    </script>
  </head>
  <body>
    <div class="main">
      <h1><%= title %></h1>

      <% if (!user) { %>
      <ul class="nav nav-tabs">
        <li class="nav-item">
          <a class="nav-link active" href="/login">Log in</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/signup">Sign up</a>
        </li>
      </ul>
      <% } else { %>
        <p> <span id="dialogname"><%= user %></span> 已登录 <a href="/logout"> 退出登录 </a></p>
      <% } %>
      
      <div class="container-fulid">
        <div class="sub mt-5" style="width: 50%">
            <div id="chatroom">
          
            </div>
            <div class="message">
              <form action="/sendMessage" method="post" id="sendMessageForm" class="form-inline mt-5">
                <input type="text" name="msg" id="msg" class="form-control mb-3">
                <button type="submit" class="btn btn-primary ml-md-3 mb-3" id="sendMessageBtn">Send</button>
              </form>
            </div>
        </div>
      </div>
    </div>
    <script>
      var form = document.querySelector('#sendMessageForm');
      var chatroom = document.querySelector('#chatroom');

      form.addEventListener('submit', function(event) {
        event.preventDefault();
        let messageDom = form.querySelector('#msg');
        let data = {
          username: document.querySelector("#dialogname").innerHTML,
          message: messageDom.value
        }
        console.log(data);
        socket.emit('say', data);
        messageDom.value = "";
      });

      socket.on('newsay', function(data) {
        let newMsg = createEle(`
          <div class="shadow p-3 mb-5 bg-white rounded">
            <p> <span class="text-weight-bold"> ${data.name}: </span> &nbsp;&nbsp;&nbsp; ${data.msg}  </p>
            <div class="text-muted text-center"> ${data.date} </div>
          </div>
        `);
        chatroom.appendChild(newMsg);
      });

      function createEle(html) {
        var parent = document.createElement('div');
        parent.innerHTML = html;
        return parent.firstElementChild;
      }
    </script>
  </body>
</html>
